﻿using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Windows.Forms;
using SybaseLogRecovery.Properties;

namespace SybaseLogRecovery
{
    public partial class DataBaseConnection : Form
    {
        public DataBaseConnection()
        {
            InitializeComponent();
            SetUpFields();
        }

        public void SetUpFields()
        {

            OdbcConnectionStringBuilder odbcBuilder = new OdbcConnectionStringBuilder(Settings.Default.dataConnectionString);
            textBox1.Text = Settings.Default.dataConnectionString;

            try
            {
                List<string> driverNames = new List<string>(DataBaseStatics.GetOdbcDriverNames());
                driverNames.Add(odbcBuilder["Driver"].ToString());
                comboBox1.DataSource = driverNames;
                comboBox1.SelectedItem = odbcBuilder["Driver"].ToString();

                var serverNames = DataBaseStatics.GetSybaseConnectionNames() != null ? new List<string>(DataBaseStatics.GetSybaseConnectionNames().Values) : new List<string>() { odbcBuilder["Server"].ToString() };
                //serverNames.Add(odbcBuilder["Server"].ToString());
                comboBox2.DataSource = serverNames;
                comboBox2.SelectedItem = odbcBuilder["Server"].ToString();

                textBox2.Text = odbcBuilder["Port"].ToString();
                textBox3.Text = odbcBuilder["Uid"].ToString();
                textBox4.Text = odbcBuilder["Pwd"].ToString();
                textBox5.Text = odbcBuilder["DataBase"].ToString();
            }
            catch (Exception)
            {

                Settings.Default.Reset();
            }
        }

        public string CombineUserString()
        {
            OdbcConnectionStringBuilder builder = new OdbcConnectionStringBuilder();
            // Take advantage of the Driver property. 
            builder.Driver = comboBox1.Text;
            builder["Server"] = comboBox2.Text;

            builder["Port"] = textBox2.Text;
            builder["Uid"] = textBox3.Text;
            builder["Pwd"] = textBox4.Text;
            builder["DataBase"] = textBox5.Text;


            Settings.Default.dataConnectionString = builder.ToString();
            textBox1.Text = Settings.Default.dataConnectionString;
            Settings.Default.Save();
            return builder.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CombineUserString();
            if (DataBaseStatics.ConnectionCheck())
            {
                this.Close();
            }
            else
            {
                label6.Text = "Неверно указана строка подключения!";
            }

        }


    }
}
